﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.Interfaces ;
using Medianamik.UI.Lock;
using Medianamik.Core.Lock;

namespace Medianamik.UI.ConfigManagement
{
    public partial class LockList : BasePage 
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindControls();

            }
        }

        private void BindControls()
        {
            var locks = (from l in LockManager.GetLocks(0, int.MaxValue)
                        select l).ToArray();
            var relatedNodes = NodeManager.GetNodes(locks.Select(l => l.LockObject).Distinct().ToArray());

            var dataSource = (from l in locks
                             let nodeName = relatedNodes.Where(n => n.ID == l.LockObject).Select(n => n.Name).FirstOrDefault() ?? string.Empty
                             select new 
                             { 
                                 LockId = l.LockId ,
                                 ActivationDate = l.ActivationDate ,
                                 IsAlive = l.IsAlive(),
                                 NodeName = nodeName 
                             }).OrderByDescending(l=> l.ActivationDate ?? DateTime.MinValue);

            GridLocks.DataSource = dataSource.ToArray();
            GridLocks.DataBind();
        }

        protected void GridLocks_ItemCommand(object sender, CommandEventArgs e)
        {
            switch (e.CommandName.ToLowerInvariant())
            {
                case "deletelock":
                    LockManager.DeleteLock(new Guid((string)e.CommandArgument));
                    BindControls();
                    break;
                default: break;
            }
        }

        protected void btnCleanUpLocks_Click(object sender, EventArgs e)
        {
            LockManager.CleanUpLocks();
        }
    }
}
